﻿$(document).ready(function () {
    var appOneHost = $("#oneAppControlHost>iframe");
    
    if (!window.OneAppHost) window.OneAppHost = new OneAppHostControl(appOneHost);
});

function OneAppHostControl(hostFrame) {
    this.Initialize(hostFrame);
}

OneAppHostControl.prototype.Initialize= function(hostFrame)
{
    var source = hostFrame.attr("source");
    var onerror = hostFrame.attr("onerror");
    var background = hostFrame.attr("background");
    var data = hostFrame.attr("data");
    var type = hostFrame.attr("type");
    var $that = this;
    $(hostFrame).css('background-color', background);

    $.ajax({
        url: source,
        cache:false,
        beforeSend: function (xhr) {
            xhr.overrideMimeType("text/plain; charset=x-user-defined");
        }
    }).fail( function(xhr, textStatus, errorThrown) {
        alert(errorThrown);
    }).done(function (data) {
        var buffer = data;
        var zip = new JSZip(buffer);
        $that.resources = zip;
        $that.loadApplication();
    });

    OneAppHostControl.prototype.getResources = function () {
        return this.resources;
    }
    OneAppHostControl.prototype.loadApplication = function () {
        var zip = this.getResources();
        var content = zip.file("Index.html").asText();
        var xmlDocument = $($.parseXML(content));

        var scripts = xmlDocument.find("head>script");
        var scriptContent = "";
        for (var scriptIndex = 0; scriptIndex < scripts.length; scriptIndex++) {
            var script = scripts[scriptIndex];

            if (script.src.length) {
                xmlDocument.remove(script);
                var scriptName = script.src.substring(script.src.lastIndexOf("/")).replace("/", "");
                if (scriptName.length && zip.file(scriptName)) {
                    var jsFile = zip.file(scriptName).asText();
                    scriptContent += "<script> " + jsFile + " </script>";
                }
            }
        }

        scriptContent += '<script>$("body").load(OneApp.load());</script>';
        var $frame = $("#oneAppControlHost>iframe");
        var doc = $frame[0].contentWindow.document;
        doc.write(content + scriptContent);
        setTimeout(function () {
            $(document).attr("title", doc.title);
            window.location.href = "#Index.html";
        }, 1);
    }
}

